package com.hougong.lineclient.transport;



import com.hougong.lineclient.common.GlobalCode;
import com.hougong.lineclient.utils.SendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 心跳发送
 */
public class HeartBeatTask {
    public static final Logger LOGGER=LoggerFactory.getLogger(HeartBeatTask.class);
    private static HeartBeatTask heartBeatTask =null;
    private   long millsInterval = 30*1000; //间隔
    private Timer timer;
    private TimerTask timerTask;
    public  long getMillsInterval() {
        return millsInterval;
    }

    public  void setMillsInterval(long millsInterval) {
        this.millsInterval = millsInterval;
    }

    private HeartBeatTask() {
    }

    public static HeartBeatTask getInstance() {
        if(heartBeatTask==null){
            synchronized (HeartBeatTask.class){
                if(heartBeatTask==null){
                    heartBeatTask=new HeartBeatTask();
                }
            }
        }
        return heartBeatTask;
    }

    public void startTask(long millsInterval) {
        this.millsInterval = millsInterval;
        timer=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
                if(ClientConfig.channel!=null){
                    SendUtils.sendRequest(GlobalCode.Client_HeartBeat.getBizCode(),null);
                    LOGGER.debug("发送服务器心跳...");
                }
            }
        };
        timer.schedule(timerTask,1000,millsInterval);
    }

    public void startTask() {
        cancelTask();
        startTask(this.millsInterval);
    }

    public void cancelTask() {
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
        if(timerTask!=null){
            timerTask.cancel();
            timerTask=null;
        }
    }

    public void resetTask(long millsInterval){
        cancelTask();
        startTask(millsInterval);
    }
}
